Some Basic NumPy functionality (attributes, array creation, basic operations between arrays, and basic operations on one array). Adapted from https://docs.scipy.org/doc/numpy-dev/user/quickstart.html
In [1]:
#"NumPy's main object is the homogeneous multidimensional array"
import numpy as np
arr = np.array([[0,1,2],[3,4,5]])
arr
Out[1]:
In [2]:
#Array class (also known as array but np.array is not the same as standard python's array.array)
type(arr)
Out[2]:
In [3]:
#Number of axes (also known as rank)
arr.ndim
Out[3]:
In [4]:
#Dimensions of the array (n rows by m columns)
arr.shape
Out[4]:
In [5]:
#Total number of elements (product of shape)
arr.size
Out[5]:
In [6]:
#Type of elements in the array (inferred if not specified)
arr.dtype
Out[6]:
In [7]:
#Array from nested lists
arr = np.array([[1,2,3],[4,5,6]])
arr
Out[7]:
In [8]:
#Array of zeros
np.zeros((2,3))
Out[8]:
In [9]:
#Array of ones
np.ones((2,3))
Out[9]:
In [10]:
#"Empty" array
np.empty((2,3))
Out[10]:
In [11]:
#Sequence of numbers - similar to range
np.arange(0,50,10) #Start, stop, step
Out[11]:
In [12]:
#Sequence of numbers - specific number of elements specified
np.linspace(0,50,5) #Start, stop, number of elements
Out[12]:
In [13]:
#Sequence of numbers - with specific shape
np.arange(6).reshape(2,3)
Out[13]:
In [14]:
a = np.arange(0,100,10)
b = np.arange(10)
In [15]:
a
Out[15]:
In [16]:
b
Out[16]:
In [17]:
#Element-wise subtraction
a-b
Out[17]:
In [18]:
#Element-wise addition
a+b
Out[18]:
In [19]:
#Matrix multiplication
np.dot(a,b)
Out[19]:
In [20]:
#Matrix multiplication (option 2)
a.dot(b)
Out[20]:
In [21]:
arr = np.arange(12).reshape(3,4)
arr
Out[21]:
In [22]:
#Sum of all elements (as if a flat list)
arr.sum()
Out[22]:
In [23]:
#Min of all elements (as if a flat list)
a.min()
Out[23]:
In [24]:
#Max of all ements (as if a flat list)
a.max()
Out[24]:
In [25]:
#Column sum (axis=1 for row sum)
arr.sum(axis=0)
Out[25]:
In [26]:
#Column min (axis=1 for row min)
arr.sum(axis=0)
Out[26]:
In [27]:
#Culumulative sum along column (axis=1 for row)
arr.cumsum(axis=0)
Out[27]:
In [28]:
#Exponentiation
arr = np.arange(3)
np.exp(arr)
Out[28]:
In [29]:
#Square roote
np.sqrt(arr)
Out[29]: